package com.iplus.ydkf.ehome.common.net;


import android.util.Log;

import com.iplus.ydkf.ehome.App;

import java.util.Map;

import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by liuhaitian on 16/5/27.
 */
public class NetClient {
    private static OkHttpClient client;

    /**
     * @param Url      访问地址
     * @param callback 回调方法
     * @param maps     传入参数,第一个是header,第二个是body
     */
    public static void sendGetRequest(String Url, Callback<?> callback, Map<String, String>... maps) {
        Log.d("NetClient", "url: " + Url);
        if (client == null)
            client = new OkHttpClient();
        if (Url.endsWith("/"))
            Url = Url.substring(0, Url.length() - 7);
        Url += "?";
        Headers.Builder headerBuilder = new Headers.Builder();
        if (maps.length == 0) {

        } else if (maps.length == 1) {
            for (Map.Entry<String, String> entry : maps[0].entrySet()) {
                headerBuilder.add(entry.getKey(), entry.getValue());
            }
        } else if (maps.length == 2) {
            for (Map.Entry<String, String> entry : maps[0].entrySet()) {
                headerBuilder.add(entry.getKey(), entry.getValue());
            }
            for (Map.Entry<String, String> entry : maps[1].entrySet()) {
                Url += entry.getKey() + "=" + entry.getValue();
            }
        }
        Headers headers = headerBuilder.build();
        Request request = new Request.Builder().url(Url).headers(headers).get().build();
        client.newCall(request).enqueue(callback);
    }

    public static void sendPostRequest(String Url, RequestBody requestBody, Callback<?> callback) {
        Log.d("NetClient", "url: " + Url);
        if (client == null)
            client = new OkHttpClient();
        Request request = new Request.Builder().url(Url).post(requestBody).header("userId", App.getCurrentUser().getObjectId())
                .build();
        client.newCall(request).enqueue(callback);
    }

    public static void sendDelRequest(String Url, Callback<?> callback) {
        Log.d("NetClient", "url: " + Url);
        if (client == null)
            client = new OkHttpClient();
        Request request = new Request.Builder().url(Url).delete().header("userId", App.getCurrentUser()
                .getObjectId())
                .build();
        client.newCall(request).enqueue(callback);
    }
}
